package com.tanhua.server.interceptor;

import com.tanhua.domain.db.User;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 统一token处理拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("统一token处理拦截器--->前置处理");

        // 1.从请求中获取token
        String token = request.getHeader("Authorization");

        if(StringUtils.isEmpty(token)){
            // 如果token为空，认证失败
            response.setStatus(401);


        return false;
        }

        // 2.根据token获取用户
        User user = userService.findUserByToken(token);

        if (user == null) {
            // 如果用户认证失败，返回401
            response.setStatus(401);

            return false;
        }

        // 3.将当前登录用户的信息放到当前线程
        UserHolder.set(user);

        return true;
    }
}
